package top.zhdev.community.interceptor;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import top.zhdev.community.entity.User;
import top.zhdev.community.service.MessageService;
import top.zhdev.community.utils.HostHolder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 消息拦截器，在首页显示未读消息数量
 */
@Component
public class MessageInterceptor implements HandlerInterceptor {
    private HostHolder hostHolder;
    private MessageService messageService;

    @Autowired
    public void setHostHolder(HostHolder hostHolder) {
        this.hostHolder = hostHolder;
    }

    @Autowired
    public void setMessageService(MessageService messageService) {
        this.messageService = messageService;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        User user = hostHolder.getUser();
        if(user != null && modelAndView != null){
            int noticeUnreadCount = messageService.getNoticeUnreadCount(user.getId(), null);
            int letterUnreadCount = messageService.getLetterUnreadCount(user.getId(),null);
            modelAndView.addObject("allUnreadCount",noticeUnreadCount + letterUnreadCount);
        }
    }
}
